#!/bin/bash

# OpenAPI Markdown文档生成脚本

echo "开始生成OpenAPI Markdown文档..."

# 编译项目
mvn clean compile
if [ $? -ne 0 ]; then
    echo "项目编译失败!"
    exit 1
fi

# 创建target目录（如果不存在）
mkdir -p target

# 启动应用并生成JSON文档
echo "启动应用并生成JSON文档..."
mvn spring-boot:run > target/app.log 2>&1 &
APP_PID=$!

# 等待应用启动
echo "等待应用启动..."
for i in {1..30}; do
    if curl -s http://localhost:8080/v3/api-docs > /dev/null; then
        echo "应用已启动!"
        break
    fi
    echo "等待中... ($i/30)"
    sleep 2
done

# 检查应用是否成功启动
if ! curl -s http://localhost:8080/v3/api-docs > /dev/null; then
    echo "应用启动失败!"
    kill $APP_PID 2>/dev/null
    exit 1
fi

# 使用curl获取OpenAPI JSON文档
echo "获取OpenAPI JSON文档..."
curl -o target/openapi.json http://localhost:8080/v3/api-docs
if [ $? -ne 0 ]; then
    echo "获取OpenAPI JSON文档失败!"
    kill $APP_PID 2>/dev/null
    exit 1
fi

# 停止应用
echo "停止应用..."
kill $APP_PID 2>/dev/null

# 等待应用停止
sleep 3

# 检查JSON文件是否存在
if [ ! -f "target/openapi.json" ]; then
    echo "OpenAPI JSON文件不存在!"
    exit 1
fi

# 创建一个简单的Java程序来转换JSON为Markdown
echo "创建转换程序..."
cat > target/MarkdownConverter.java << 'EOF'
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class MarkdownConverter {
    public static void main(String[] args) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> openApiSpec = mapper.readValue(new File("target/openapi.json"), Map.class);
            
            StringBuilder markdown = new StringBuilder();
            
            // 添加标题和基本信息
            Map<String, Object> info = (Map<String, Object>) openApiSpec.get("info");
            String title = (String) info.get("title");
            String description = (String) info.get("description");
            String version = (String) info.get("version");
            
            markdown.append("# ").append(title).append("\n\n");
            markdown.append("**版本**: ").append(version).append("\n\n");
            markdown.append("**描述**: ").append(description).append("\n\n");
            
            // 添加路径信息
            markdown.append("## API 接口\n\n");
            Map<String, Object> paths = (Map<String, Object>) openApiSpec.get("paths");
            
            for (Map.Entry<String, Object> pathEntry : paths.entrySet()) {
                String path = pathEntry.getKey();
                Map<String, Object> pathItem = (Map<String, Object>) pathEntry.getValue();
                
                for (Map.Entry<String, Object> methodEntry : pathItem.entrySet()) {
                    String method = methodEntry.getKey().toUpperCase();
                    Map<String, Object> operation = (Map<String, Object>) methodEntry.getValue();
                    
                    markdown.append("### ").append(method).append(" ").append(path).append("\n\n");
                    
                    // 添加操作描述
                    if (operation.containsKey("summary")) {
                        markdown.append("**摘要**: ").append(operation.get("summary")).append("\n\n");
                    }
                    if (operation.containsKey("description")) {
                        markdown.append("**描述**: ").append(operation.get("description")).append("\n\n");
                    }
                    
                    // 添加参数
                    if (operation.containsKey("parameters")) {
                        markdown.append("#### 参数\n\n");
                        markdown.append("| 名称 | 位置 | 描述 | 必填 | 类型 |\n");
                        markdown.append("|------|------|------|------|------|\n");
                        
                        List<Map<String, Object>> parameters = (List<Map<String, Object>>) operation.get("parameters");
                        for (Map<String, Object> param : parameters) {
                            String name = (String) param.get("name");
                            String in = (String) param.get("in");
                            String paramDesc = param.containsKey("description") ? (String) param.get("description") : "";
                            Boolean required = param.containsKey("required") ? (Boolean) param.get("required") : false;
                            String type = param.containsKey("schema") ? 
                                    ((Map<String, Object>) param.get("schema")).get("type").toString() : 
                                    (param.containsKey("type") ? param.get("type").toString() : "");
                            
                            markdown.append("| ").append(name).append(" | ").append(in).append(" | ")
                                    .append(paramDesc).append(" | ").append(required ? "是" : "否").append(" | ")
                                    .append(type).append(" |\n");
                        }
                        markdown.append("\n");
                    }
                    
                    // 添加响应
                    if (operation.containsKey("responses")) {
                        markdown.append("#### 响应\n\n");
                        markdown.append("| 状态码 | 描述 |\n");
                        markdown.append("|--------|------|\n");
                        
                        Map<String, Object> responses = (Map<String, Object>) operation.get("responses");
                        for (Map.Entry<String, Object> responseEntry : responses.entrySet()) {
                            String statusCode = responseEntry.getKey();
                            Map<String, Object> response = (Map<String, Object>) responseEntry.getValue();
                            String respDesc = (String) response.get("description");
                            
                            markdown.append("| ").append(statusCode).append(" | ").append(respDesc).append(" |\n");
                        }
                        markdown.append("\n");
                    }
                    
                    markdown.append("---\n\n");
                }
            }
            
            // 写入Markdown文件
            try (FileWriter writer = new FileWriter("target/api-documentation.md")) {
                writer.write(markdown.toString());
            }
            
            System.out.println("Markdown文档已生成: target/api-documentation.md");
        } catch (IOException e) {
            System.err.println("转换OpenAPI文档为Markdown时出错: " + e.getMessage());
            e.printStackTrace();
            System.exit(1);
        }
    }
}
EOF

# 编译并运行转换程序
echo "编译并运行转换程序..."
javac -cp "$(mvn dependency:build-classpath -Dmdep.outputFile=/dev/stdout -q)" target/MarkdownConverter.java
java -cp ".:target:$(mvn dependency:build-classpath -Dmdep.outputFile=/dev/stdout -q)" MarkdownConverter

echo "OpenAPI Markdown文档生成完成!"
echo "文档位置: target/api-documentation.md"